package com.daisuxia.risk.service;

import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSON;
import com.antgroup.zmxy.openplatform.api.DefaultZhimaClient;
import com.antgroup.zmxy.openplatform.api.request.ZhimaAuthInfoAuthorizeRequest;
import com.antgroup.zmxy.openplatform.api.request.ZhimaAuthInfoAuthqueryRequest;
import com.antgroup.zmxy.openplatform.api.request.ZhimaCreditScoreGetRequest;
import com.antgroup.zmxy.openplatform.api.request.ZhimaCreditWatchlistiiGetRequest;
import com.antgroup.zmxy.openplatform.api.response.ZhimaAuthInfoAuthqueryResponse;
import com.antgroup.zmxy.openplatform.api.response.ZhimaCreditScoreGetResponse;
import com.antgroup.zmxy.openplatform.api.response.ZhimaCreditWatchlistiiGetResponse;
import com.daisuxia.back.utils.ServiceResult;
import com.daisuxia.back.utils.SysCacheUtils;
import com.daisuxia.risk.pojo.RiskCreditUser;
import com.daisuxia.risk.pojo.RiskOrders;
import com.daisuxia.risk.utils.ConstantRisk;
import com.daisuxia.risk.utils.GetHttp;
import com.daisuxia.web.pojo.BackConfigParams;
import com.daisuxia.web.util.OrderNoUtil;

/**
 * 
 * 类描述：芝麻信用相关接口 <br>
 * 每次发出请求之前插入订单信息，返回后更新订单信息<br>
 * 此类不做任何业务处理，仅拼接参数请求第三方，必须使用trycath，并且不向上抛出异常以保证插入或更新的订单不会回滚<br>
 * 创建人：fanyinchuan<br>
 * 创建时间：2016-12-12 下午03:41:28 <br>
 * 
 * @version
 * 
 */
@Service
public class ZmxyService implements IZmxyService {
	Logger logger = LoggerFactory.getLogger(getClass());
	@Autowired
	private IRiskOrdersService riskOrdersService;

	@Override
	public ServiceResult getOpenId(HashMap<String, Object> params) {
		ServiceResult serviceResult = new ServiceResult("500", "未知异常，请稍后重试！");
		try {
			Object userName = params.get("userName");
			Object cardNum = params.get("cardNum");
			Object userId = params.get("userId");
			if (userName != null && cardNum != null && userId != null) {
				Map<String, String> keys = SysCacheUtils
						.getConfigParams(BackConfigParams.ZMXY);
				String zmUrl = keys.get("zm_url");
				String appId = keys.get("zm_appId");
				String privateKey = keys.get("zm_private_key");
				String zhimaPublicKey = keys.get("zm_public_key");
				ZhimaAuthInfoAuthqueryRequest req = new ZhimaAuthInfoAuthqueryRequest();
				req.setIdentityType("2");// 必要参数
				/*********** 需要商户传递的参数 ***********/
				req.setIdentityParam("{\"certNo\":\"" + cardNum
						+ "\",\"certType\":\"IDENTITY_CARD\",\"name\":\""
						+ userName + "\"}");// 必要参数
				/*********** 需要商户传递的参数 ***********/
				DefaultZhimaClient client = new DefaultZhimaClient(zmUrl,
						appId, privateKey, zhimaPublicKey);
				RiskOrders orders = new RiskOrders();
				orders.setUserId(userId + "");
				orders.setOrderType(ConstantRisk.ZMXY);
				orders.setAct(ConstantRisk.GET_OPENID);
				orders.setOrderNo(OrderNoUtil.getInstance().getUUID());
				orders.setReqParams(JSON.toJSONString(req));
				logger.info("send to get openid " + orders.toString());
				riskOrdersService.insert(orders);
				ZhimaAuthInfoAuthqueryResponse response = client.execute(req);
				logger.info("get openId response=" + response);
				if (response.isSuccess()) {
					if (response.getAuthorized()) {
						serviceResult = new ServiceResult(
								ServiceResult.SUCCESS, response.getOpenId());
						orders.setStatus(RiskOrders.STATUS_SUC);
					} else {
						serviceResult = new ServiceResult("100",
								"用户未授权，请发起授权请求！");
					}
				} else {
					serviceResult = new ServiceResult("300", response
							.getErrorMessage());
				}
				orders.setReturnParams(JSON.toJSONString(response));
				riskOrdersService.update(orders);
			} else {
				serviceResult = new ServiceResult("400", "必要参数不足！");
			}
		} catch (Exception e) {
			logger.error("getOpenId error ,params=" + params, e);
		}
		
		return serviceResult;
	}

	@Override
	public ServiceResult getURL(HashMap<String, Object> params,
			HttpServletRequest request) {
		ServiceResult serviceResult = new ServiceResult("500", "未知异常，请稍后重试！");
		try {
			Object userName = params.get("userName");
			Object cardNum = params.get("cardNum");
			Object userId = params.get("userId");
			if (userName != null && cardNum != null && userId != null) {
				Map<String, String> keys = SysCacheUtils
						.getConfigParams(BackConfigParams.ZMXY);
				String zmUrl = keys.get("zm_url");
				String appId = keys.get("zm_appId");
				String privateKey = keys.get("zm_private_key");
				String zhimaPublicKey = keys.get("zm_public_key");
				ZhimaAuthInfoAuthorizeRequest req = new ZhimaAuthInfoAuthorizeRequest();
				req.setIdentityType("2");
				String channel = "apppc";
				String auth_code = "M_APPPC_CERT";
				String state = userId + "";
				if (GetHttp.isMobileDevice(request)) {
					channel = "app";
					auth_code = "M_H5";
				}
				// 必要参数 state: 用于给商户提供透传的参数，芝麻会将此参数透传给商户;
				req.setChannel(channel);
				req.setBizParams("{\"auth_code\":\"" + auth_code
						+ "\",\"state\":\"" + state + "\"}");
				// 必要参数
				req.setIdentityParam("{\"certNo\":\"" + cardNum
						+ "\",\"certType\":\"IDENTITY_CARD\",\"name\":\""
						+ userName + "\"}");
				RiskOrders orders = new RiskOrders();
				orders.setUserId(userId + "");
				orders.setOrderType(ConstantRisk.ZMXY);
				orders.setAct(ConstantRisk.GET_URL);
				orders.setOrderNo(OrderNoUtil.getInstance().getUUID());
				orders.setReqParams(JSON.toJSONString(req));
				logger.info("send to  getURL " + orders.toString());
				riskOrdersService.insert(orders);
				DefaultZhimaClient client = new DefaultZhimaClient(zmUrl,
						appId, privateKey, zhimaPublicKey);
				String url = client.generatePageRedirectInvokeUrl(req);
				logger.info("get getAuthorizeUrl url=" + url);
				orders.setStatus(RiskOrders.STATUS_SUC);
				orders.setReturnParams(url);
				riskOrdersService.update(orders);
				serviceResult = new ServiceResult(ServiceResult.SUCCESS, url);
			} else {
				serviceResult = new ServiceResult("400", "必要参数不足！");
			}
		} catch (Exception e) {
			logger.error("getURL error ,params=" + params, e);
		}
		return serviceResult;
	}
	@Override
	public ServiceResult getZmScore(HashMap<String, Object> params) {
		ServiceResult serviceResult = new ServiceResult("500", "未知异常，请稍后重试！");
		try {
			Object userId = params.get("userId");
			Object openId = params.get("openId");
			if (userId != null && openId != null) {
				Map<String, String> keys = SysCacheUtils
						.getConfigParams(BackConfigParams.ZMXY);
				String zmUrl = keys.get("zm_url");
				String appId = keys.get("zm_appId");
				String privateKey = keys.get("zm_private_key");
				String zhimaPublicKey = keys.get("zm_public_key");
				ZhimaCreditScoreGetRequest req2 = new ZhimaCreditScoreGetRequest();
				req2.setProductCode("w1010100100000000001");// 必要参数
				req2.setOpenId(openId + "");// 必要参数
				req2.setTransactionId(OrderNoUtil.getInstance().getUUID());
				RiskOrders orders = new RiskOrders();
				orders.setUserId(userId + "");
				orders.setOrderType(ConstantRisk.ZMXY);
				orders.setAct(ConstantRisk.GET_SCORE);
				orders.setOrderNo(OrderNoUtil.getInstance().getUUID());
				orders.setReqParams(JSON.toJSONString(req2));
				logger.info("send to get openid " + orders.toString());
				riskOrdersService.insert(orders);
				DefaultZhimaClient client2 = new DefaultZhimaClient(zmUrl,
						appId, privateKey, zhimaPublicKey);
				ZhimaCreditScoreGetResponse response2 = client2.execute(req2);
				logger.info("get score response=" + response2);
				if (response2.isSuccess()) {
					serviceResult = new ServiceResult(ServiceResult.SUCCESS,
							response2.getZmScore());
					orders.setStatus(RiskOrders.STATUS_SUC);
				} else {
					serviceResult = new ServiceResult("300", response2
							.getErrorMessage());
				}
				orders.setReturnParams(JSON.toJSONString(response2));
				riskOrdersService.update(orders);
			} else {
				serviceResult = new ServiceResult("400", "必要参数不足！");
			}
		} catch (Exception e) {
			logger.error("getZmScore error ,params=" + params, e);
		}
	
		return serviceResult;
	}

	@Override
	public ServiceResult getCreditWatchList(HashMap<String, Object> params) {
		ServiceResult serviceResult = new ServiceResult("500", "未知异常，请稍后重试！");
		try {
			Object userId = params.get("userId");
			Object openId = params.get("openId");
			if (userId != null && openId != null) {
				Map<String, String> keys = SysCacheUtils
						.getConfigParams(BackConfigParams.ZMXY);
				String zmUrl = keys.get("zm_url");
				String appId = keys.get("zm_appId");
				String privateKey = keys.get("zm_private_key");
				String zhimaPublicKey = keys.get("zm_public_key");
				ZhimaCreditWatchlistiiGetRequest creditWatchlistGetRequest = new ZhimaCreditWatchlistiiGetRequest();
				creditWatchlistGetRequest.setPlatform("zmop");
				creditWatchlistGetRequest.setChannel("apppc");
				creditWatchlistGetRequest.setTransactionId(OrderNoUtil
						.getInstance().getUUID());
				creditWatchlistGetRequest
						.setProductCode("w1010100100000000022");
				creditWatchlistGetRequest.setOpenId(openId + "");
				RiskOrders orders = new RiskOrders();
				orders.setUserId(userId + "");
				orders.setOrderType(ConstantRisk.ZMXY);
				orders.setAct(ConstantRisk.GET_INDUSTY);
				orders.setOrderNo(OrderNoUtil.getInstance().getUUID());
				orders.setReqParams(JSON
						.toJSONString(creditWatchlistGetRequest));
				logger.info("send getCreditWatchList " + orders.toString());
				riskOrdersService.insert(orders);
				DefaultZhimaClient client = new DefaultZhimaClient(zmUrl,
						appId, "utf-8", privateKey, zhimaPublicKey);
				ZhimaCreditWatchlistiiGetResponse response1 = client
						.execute(creditWatchlistGetRequest);
				logger.info("getCreditWatchList response=" + response1);
				if (response1.isSuccess()) {
					serviceResult = new ServiceResult(ServiceResult.SUCCESS,
							JSON.toJSONString(response1));
					orders.setStatus(RiskOrders.STATUS_SUC);
				} else {
					serviceResult = new ServiceResult("300", response1
							.getErrorMessage());
				}
				orders.setReturnParams(JSON.toJSONString(response1));
				riskOrdersService.update(orders);
			} else {
				serviceResult = new ServiceResult("400", "必要参数不足！");
			}
		} catch (Exception e) {
			logger.error("getCreditWatchList error ,params=" + params, e);
		}
		
		return serviceResult;
	}

}
